import json
import re
import token

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse

# Create your views here.
from django.views import View

from apps.users.utils import check_verify_token, generate_verify_token
from celery_tasks.email.tasks import send_verify_mail
from apps.users.models import User, Address
from utils.viewmixin import LoginMixin


class UsernameCountView(View):

    def get(self, request, username):
        # 步骤
        # 接收用户名
        print(username)
        # 根据用户名查数据库
        count = User.objects.filter(username=username).count()
        # 返回响应
        return JsonResponse({'count': count, 'code': '0', 'errmsg': 'ok'})

class RegisterView(View):

    def post(self, request):
        # 步骤
        # 接受请求
        body_byte = request.body
        # 获取json格式数据，转为字典
        body_dict = json.loads(body_byte)

        # 获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 验证数据
        # 验证是否为空,有没有传
        # all里传入列表,如果列表里,任一元素为flase或者空,结果就是flase
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": "400", "errmsg": "register fail"})
        #正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "register fail"})

        # 生成用户保存到数据库
        # create_user自动为密码进行加密
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': '400', 'errmsg': '用户保存失败，检查用户信息'})

        print('保存用户到数据库成功')

        # 状态保持
        login(request, user)

        respone = JsonResponse({'code': '0', 'errmsg': 'ok'})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        respone.set_cookie('username', user.username, max_age=3600 * 24 * 7)

        # 返回响应
        return respone


class LoginView(View):
    
    def post(self, request):
        # 接收数据
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get('username')
        password = data_dict.get('password')
        remembered = data_dict.get('remembered')

        # 验证数据,是否为空
        if not all([username, password, remembered]):
            return JsonResponse({'code': '400', 'errmsg': '参数不全'})

        # 根据用户传入的username的值 判断是手机号还是用户名
        # 然后设置用户验证是使用手机还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 验证用户名或验证码是否正确
        # 如果正确返回user对象,否则返回None
        user = authenticate(username=username, password=password)

        if user is None:
            return JsonResponse({'code': '400', 'errmsg': '用户名或密码错误'})

        # 状态保持 session
        login(request, user)

        # 判断是否记住登录, 设置session的有效期
        if remembered:
            # 记住登录 默认2周
            request.session.set_expiry(None)
        else:
            # 不记住登录 浏览器关闭 session过期
            request.session.set_expiry(0)

        respone = JsonResponse({'code': '0', 'errmsg': 'ok'})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        respone.set_cookie('username', user.username, max_age=3600 * 24 * 7)

        # 返回响应
        return respone

class LogoutView(View):

    def delete(self, request):
        # 调用logout清空状态保持的session
        logout(request)

        # 删除cookie里的username
        response = JsonResponse({'code': '0', 'errmsg': 'ok'})
        response.delete_cookie('username')

        # 返回响应
        return response

class UserInfoView(LoginMixin, View):

    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }

        return JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            'info_data': info_data
        })

class SaveEmailView(View):

    def put(self, request):
        # 获取邮箱地址数据
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get('email')
        # 校验数据
        if not email:
            return JsonResponse({'code': '400', 'errmsg': '邮箱地址不能为空'})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': '400', 'errmsg': '邮箱地址格式错误'})

        try:
            # 保存邮箱地址
            request.user.email = email
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': '400', 'errmsg': '邮箱保存失败'})

        # 发送邮件
        print('发送邮件给用户---', email)
        subject = 'f14战斗机便宜买'
        recipient_list = [email]

        token = generate_verify_token(request.user.id)
        # print('token---------------', token)
        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
        html_message = '<p>尊敬的用户您好！</p>'\
                       '<p>本商城观摩用户您最近有购买战斗机的想法。</p>'\
                       '<p>却无奈手头拮据,迟迟没有下单。</p>'\
                       '<p>本商城最看不得这种想要买又没有钱的事情了。</p>'\
                       '<p>所以本商城决定给用户您一折购买战斗机的机会。</p>'\
                       '<p>点击此链接激活您的邮箱%s赶快下单吧：</p>'\
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        print('123')
        # 当前问题:此行不执行
        send_verify_mail.delay(subject=subject, html_message=html_message, recipient_list=recipient_list)
        print('456')
        # 返回响应
        return JsonResponse({'code': '0', 'errmsg': 'ok'})

class EmailVerifyView(View):

    def put(self, request):
        # 获取参数
        token = request.GET.get('token')
        # 校验参数
        if token is None:
            return JsonResponse({"code": "400", "errmsg": "缺少token"})
        # 解密获取user_id
        user_id = check_verify_token(token)
        # 判断user_id是否为空
        if user_id is None:
            return JsonResponse({"code": "400", "errmsg": "token错误"})
        try:
            # 查询用户 数据
            user = User.objects.get(id = user_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "查询不到用户"})
        # 修改用户邮箱激活字段为True
        user.email_active = True
        user.save()
        # 返回响应
        return JsonResponse({"code": "0", "errmsg": "ok"})

class AddressCreateView(LoginMixin, View):

    def post(self, request):
        # 接收请求
        body = request.body
        data_dict = json.loads(body)
        # 获取参数
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')

        print('获取成功')
        # 验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 正则验证
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号码格式错误'})
        # 保存数据到数据库
        user = request.user
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400,'errmsg': '保存数据失败'})

        print('保存成功')

        # 数据转为字典
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        # 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "address": address_dict})

class AddressView(LoginMixin, View):

    def get(self, request):
        # 获取用户对象
        user = request.user
        # 查询当前用户的所有地址信息
        addresses = Address.objects.filter(user=user, is_deleted=False) #is_deleted=False过滤查询没有删除的
        # 转为字典数据
        address_list = []
        for address in addresses:
            address_list.append({
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email,
            })
            # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_list})

# # class AddressDeleteView(LoginMixin, View):
#
#     def delete(self, request, index):
#
#         del_add = Address.objects.filter(id=index).update(is_deleted=True)
#
#         return JsonResponse({'code': 0, 'errmsg': 'ok'})
#
# # class AddressChangeView(LoginMixin, View):
#
#     def put(self, request, index):
#         body = request.body
#         data_dict = json.loads(body)
#         # 获取参数
#         receiver = data_dict.get('receiver')
#         province_id = data_dict.get('province_id')
#         city_id = data_dict.get('city_id')
#         district_id = data_dict.get('district_id')
#         place = data_dict.get('place')
#         mobile = data_dict.get('mobile')
#         tel = data_dict.get('tel')
#         email = data_dict.get('email')
#         # 修改参数
#         address = Address.objects.filter(id=index).update(
#             # title=receiver,
#             receiver=receiver,
#             province_id=province_id,
#             city_id=city_id,
#             district_id=district_id,
#             place=place,
#             mobile=mobile,
#             tel=tel,
#             email=email,
#         )
#         return JsonResponse({'code': 0, 'errmsg': 'ok'})



